package com.lcy.struct.bTreePlus.disk.serialize;

import com.lcy.struct.bTreePlus.disk.core.BPlusTree;
import com.lcy.struct.bTreePlus.disk.core.BPlusTreeFactory;
import com.lcy.struct.bTreePlus.property.BPlusFileInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lucongyang
 * @date Created in  9:38
 * @description 序列化中心
 */
public class SerializeCenter {
    private Map<Long, BPlusTree> needSerializeMap;

    public static SerializeCenter getInstance() {
        return SerializeCenterHandler.INSTANCE;
    }

    public void addNeedSerialize(BPlusTree bPlusTree) {
        needSerializeMap.put(bPlusTree.getPosition(), bPlusTree);
        BPlusTreeFactory.addCache(bPlusTree);
    }

    public void serializeCacheNeed() {
        // 持久化
        int n = 100;
        if (needSerializeMap.size() > n) {
            System.out.println("需要持久化的节点有" + needSerializeMap.size() + "个");
        }
        int i = 0;
        long a2;
        long a1 = System.currentTimeMillis();
        for (Map.Entry<Long, BPlusTree> m : needSerializeMap.entrySet()) {
            m.getValue().serializeToFile();
            if (++i % n == 0) {
                a2 = System.currentTimeMillis();
                System.out.println("已持久化：" + i + "条数据,总共耗时：" + (a2 - a1) + "毫秒");
                a1 = a2;
            }
        }
        BPlusTreeFactory.saveHeaderInfo();
        BPlusFileInfo.saveCount();
        needSerializeMap.clear();
    }

    private static class SerializeCenterHandler {
        private static final SerializeCenter INSTANCE = new SerializeCenter();
    }

    private SerializeCenter() {
        needSerializeMap = new HashMap<>();
    }
}
